/**
 * 类型判断方法
 * @param val (type:any)
 * @param type (type:string)
 * @returns {string|boolean}
 * @constructor
 */
export function T(val, type) {
  let t = Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
  if (!type) {
    return t
  }
  if (t === type) {
    return true
  } else {
    return false
  }
}

/**
 * 数据存储方法
 * @param session (是否使用sessionStorage)
 * @returns {DOMPoint | SVGNumber | string | SVGTransform | SVGLength | SVGPathSeg | any|{set(*=, *=): void, get(*=): (*|undefined), clear(): void, del(*=): void}}
 */
export function storage(session) {
  let storage
  if (session) {
    storage = sessionStorage
  } else {
    storage = localStorage
  }
  return {
    set(key, val) {
      if (val === undefined || val === null) {
        console.error(`save val invalid,the set function can't support type of ${T(val)}`)
        return
      }
      try {
          storage.setItem(key, JSON.stringify(val))
      } catch (e) {
        storage.setItem(key, val)
      }
    },
    get(key) {
      let data = storage.getItem(key)
      try {
        return JSON.parse(data)
      } catch (e) {
        return data
      }
    },
    del(key) {
      storage.removeItem(key)
    },
    clear() {
      storage.clear()
    }
  }
}
